/**
 * 提供两个接口，show和setReason
 */
function TravelingFaultDiscMain(){
	var currentReason = "XX故障";
	var startYear;
	var endYear;
	var currentMonth = 0;
	var rightDivId = 'affectObjDiv';
	var radius = 50;//热点图的半径
	var panel;
	function show(){
		clearAll();
		panel = new PanelTablesUtil(rightDivId);
		panel.setTitle(currentReason+'故障');
		showInfo();
	}
	function hide(){
		TimelineSelector.hide();
	}
	function showInfo(){
		//改变查询模式
		var layerBtn = SelectLayerComponent.getBtn(false,changeLayer);
		panel.setTitleTool(layerBtn[0]);
		panel.setInfo(layerBtn[1]);
		
		YearModelDrawer.show();
		panel.show();
	}
	function changeLayer(){
		DrawPointComponent.redraw();
	}
	/**
	 * 年份模式
	 * 提供一个接口：
	 * show()
	 */
	var YearModelDrawer = (function(){
		var resultDiv,title;
		function show(){
			var queryDiv = QueryDivComponent.getQueryDiv(changeYear);
			panel.setInfo(queryDiv);
			title = $('<span>'+startYear+"~"+endYear+currentReason+"故障</span>");
			resultDiv = panel.getCollapsePanelEle("faultDiscYearResult",title,true);
			changeYear();
		}
		function changeYear(){
			QueryDivComponent.updateStartAndEnd();
			TimelineSelector.draw(changeYear,query);
			query(0);
		}
		//画出来结果，每次changemonth，也是query，changeyear也是。但是 changeyear需要重新画时间轴。
		function query(){
			resultDiv.html('');
			title.html(getTitle());
			resultDiv.html(PanelTablesUtil.getNoDataDiv("加载中..."));
			DrawPointComponent.clear();
			var url = '/rest/fault/getTravelingFaultByDate/'+startYear+'/'+endYear +'/'+currentMonth;
			$.ajax({
				   type: "GET",
				   url: url,
				   success: function(result){
					   result = eval('('+result+')');
					   resultDiv.html('');
					   if(result && result.tableData && result.tableData.length>0){
						   drawTable(result.tableData);
						   DrawPointComponent.draw(result.heatMapData,result.scatterMapData);
					   }else{
						   resultDiv.html(PanelTablesUtil.getSmileInfo('无故障发生'));
					   }
				   },
				   error:function(err){
					   resultDiv.html(PanelTablesUtil.getNoDataDiv('查询出错！'));
				   }
				});
		}
		function drawTable(data){
			RightTableDrawer.draw(title,resultDiv,data);
		}
		function getTitle(){
			return startYear +(startYear == endYear?'':'~'+endYear)+'年'
			+(currentMonth == 0?'':currentMonth+'月')+currentReason+'故障';
		}
		return {
			show:show
		};
	})();
	/**
	 * 画右侧表格，提供接口：draw()需要传参：表格的标题的jquery引用，表格的父的jquery引用,数据
	 */
	var RightTableDrawer = (function(){
		function getTitle(){
			return startYear +(startYear == endYear?'':'~'+endYear)+'年'
			+(currentMonth == 0?'':currentMonth+'月')+currentReason+'故障';
		}
		function draw(title,resultDiv,data){
			title.html(getTitle()+'<span title="故障次数" class="badge bg-red pull-right">'+getFaultNum(data)+'</span>');
			var table = $('<table class="table table-bordered table-hover"></table>').appendTo(resultDiv);
			var opt = MyTable.getDefaultOptions();
			opt.scrollX = false;
			opt.autoWidth = false;
			opt.scrollY = 300;
			opt.scrollCollapse = true;
			var t = new MyTable(table, ['故障设备','故障次数'], opt);
			t.setDataSet(getArrayDataset(data));
			t.show();
			t.onRowClick(function(data) {
				if (data) {
					searchSelectObj(data[0],true,false,data[2]);
				}
			});
		}
		function getFaultNum(data){
			var sum = 0;
			for(var i in data){
				sum += data[i][1];
			}
			return sum;
		}
		function getArrayDataset(data){
			var ds = [];
			for(var i in data){
				ds.push([data[i][0],data[i][1],data[i][3]]);
			}
			return ds;
		}
		function getDataset(data){
			var ds = [];
			for(var i in data){
				var t = new Date(data[i].faultTime.time);
				var d = [t.toLocaleDateString(),data[i].equipment?data[i].equipment:'',data[i].startPole?data[i].startPole:''];
				ds.push(d);
			}
			return ds;
			function sortData(obj1,obj2){
				return obj1.faultTime.time - obj2.faultTime.time;
			}
			function getDayTimeStr(millis){
				var t = new Date(millis);
				var m = t.getMonth() + 1 > 9 ? (t.getMonth() + 1) : ("0" + (t.getMonth() + 1));
				var d = t.getDate() > 9 ? t.getDate() : "0" + t.getDate();
				var timestr = t.getFullYear() + "-" + m + "-" + d;
				return timestr;
			}
		}
		return {
			draw:draw
		};
	})();
	/**
	 * 时间轴选择器，提供接口：draw(year,ms,onchangeYear,onchangeMonth),hide()
	 */
	var TimelineSelector = (function(){
		var bottomTitle = $('#bottom_title');
		var bottomDiv = $('#bottomDiv');
		var timeline = $('#bottomTimeline');
		var allMonths = [0,1,2,3,4,5,6,7,8,9,10,11,12];
		var months = [];
		
		function show(onChangeYear,onChangeMonth){
			drawBottomTitle(onChangeYear);
			drawBottomDiv(onChangeMonth);
		}
		function drawBottomDiv(callback){
			bottomDiv.css("display",'block');
			if(months && months.length == 0){
				timeline.html(PanelTablesUtil.getSmileInfo("一次设备（500kv）未发生"+currentReason+"故障。"));
			}else{
				timeLineObj = new TimeLine("bottomTimeline");
				timeLineObj.setTimeDatas(getMonths());
				var opt = timeLineObj.getOption().baseOption;
				opt.backgroundColor = 'transparent';
				opt.timeline.controlStyle.show = true;
				opt.timeline.controlStyle.showPlayBtn = false;
				opt.timeline.controlStyle.showNextBtn = true;
				opt.timeline.controlStyle.showPrevBtn = true;
				opt.timeline.top = '40%';
				opt.timeline.currentIndex = currentMonth;
				timeLineObj.show();
				timeLineObj.getChart().on('timelinechanged', function (params) {
					currentMonth = allMonths[params.currentIndex];
					callback();
				});
			}
		}
		function getMonths(){
			var ms = [];
			for(var i in allMonths){
				if(i == 0){
					ms[i] = {value:"全部",symbol:"diamond",symbolSize:18};
				}else{
					ms[i] = allMonths[i]+"月";
					for(var j in months){
						if(allMonths[i] == months[j]){
							ms[i] = {value:months[j]+"月",symbol:'diamond',symbolSize:16};
							break;
						}
					}
				}
			}
			return ms;
		}
		//title，需要两个方法，一个lastYear,ne
		function drawBottomTitle(callback){
			bottomTitle.css('display','block');
			bottomTitle.html('');
			var ul = $('<div class="btn-group"></div>').appendTo(bottomTitle);
			var lastBtn = $('<button class="btn btn-primary">'+startYear+'</button>').appendTo(ul);
			var yearBtn = $('<button class="btn btn-primary">~</button>').appendTo(ul);
			var nextBtn = $('<button class="btn btn-primary" >'+endYear+'</button>').appendTo(ul);
			var d = new Date();
			d.setFullYear(startYear);
			lastBtn.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'top-right',
				autoclose : true,
				todayHighlight : true,
				startView:4,
				endDate:new Date(),
				initialDate:d
			}).on('changeYear', function(ev){
				startYear = ev.date.getFullYear();
				callback();
			});
			var e = new Date();
			e.setFullYear(endYear);
			nextBtn.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'top-right',
				autoclose : true,
				todayHighlight : true,
				startView:4,
				endDate:new Date(),
				initialDate:e
			}).on('changeYear', function(ev){
				endYear = ev.date.getFullYear();
				callback();
			});
		}
		return {
			draw:function(onChangeYear,onChangeMonth){
				$.getJSON("/rest/fault/getTravelingFaultMonthByYear/"+startYear+"/"+endYear,function(result){
					months = result;
					show(onChangeYear,onChangeMonth);
				});
			},
			hide:function(){
				bottomTitle.css('display','none');
				bottomDiv.css('display','none');
			}
		};
	})();
	/**
	 * 选择热点图，散点图，网格图的组件
	 * 开放接口：
	 * getBtn(isShow,callback)
	 * 返回一个数组，第一个是jquery的按钮，第二个是jquery的收缩选择框
	 * 参数：isShow：收缩框默认是否显示。callback：选择发生时，调用此方法。  
	 */
	var SelectLayerComponent = (function(){
		var layerTypes = ['散点图','热点图','网格图'];
		var currentType = '热点图';
		var div,btn;
		function drawDiv(isShow,callback){
			div = $('<div class="panel-collapse collapse" />');
			var table = $('<table/>').appendTo(div);
			var tr = $('<tr/>').appendTo(table);
			for(var i in layerTypes){
				getTd(layerTypes[i]).appendTo(tr);
			}
			if(isShow){
				div.addClass('in');
			}
			function getTd(value){
				var td = $('<td/>');
				var label = $('<label />').appendTo(td);
				var input = $('<input style="margin:5px;" type="radio" value="'+value+'" name="faultLayerType">').appendTo(label);
				label.append(value);
				if(currentType == value){
					input.attr('checked','checked');
				}
				input.change(function(){
					if(this.checked){
						currentType = this.value;
						callback(this.value);
					}
				});
				return td;
			}
		}
		return {
			getBtn:function(isShow,callback){
				drawDiv(isShow,callback);
				btn = $('<i class="fa fa-cogs"></i>');
				btn.click(function(){
					div.collapse('toggle');
				});
				return [btn,div];
			},
			getCurrentType:function(){
				return currentType;
			}
		};
	})();
	/**
	 * 查询组件
	 * 提供两个接口：getQueryDiv(callback)
	 * callback:查询方法
	 */
	var QueryDivComponent = (function() {
		var div,restore,query,minus,start,end;
		startYear = endYear = new Date().getFullYear();
		
		function getQueryDiv(callback){
			div = $('<div style="display:flex;"/>');
			minus = $('<span class="btn btn-default" ><i class="fa fa-arrow-left"></i></span>').appendTo(div);
			start = $('<input type="text" class="form-control ice-warning-start"/>').appendTo(div);
			end = $('<input type="text" class="form-control ice-warning-end"/>').appendTo(div);
			restore = $('<span class="btn btn-default" ><i class="fa fa-repeat"></i></span>').appendTo(div);
			query = $('<span class="btn btn-default" >搜索</span>' ).appendTo(div);
			
			query.click(function(){
				startYear = start.val();
				endYear = end.val();
				if(endYear>new Date().getFullYear()){
					endYear = new Date().getFullYear();
				}
				callback();
			});
			restore.click(function(){
				startYear = endYear = new Date().getFullYear();
				start.val(startYear);
				end.val(endYear);
			});
			minus.click(function(){
				startYear = Number(startYear)-1;
				start.val(startYear);
				endYear = Number(endYear)-1;
				end.val(endYear);
			});
			start.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'bottom-right',
				autoclose : true,
				startView:4,
				endDate:new Date(),
				initialDate:new Date()
			}).on('changeYear', function(ev){
				startYear = ev.date.getFullYear();
			});
			end.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'bottom-left',
				autoclose : true,
				startView:4,
				endDate:new Date(),
				initialDate:new Date()
			}).on('changeYear', function(ev){
				endYear = ev.date.getFullYear();
			});
			start.val(startYear);
			end.val(endYear);
			return div;
		}
		return {
			getQueryDiv:getQueryDiv,
			updateStartAndEnd:function(){
				start.val(startYear);
				end.val(endYear);
			}
		};
	})();
	/**
	 * 根据layer画图，提供两个接口：draw(data),redraw(),clear()
	 */
	var DrawPointComponent = (function(){
		var layerTypes = {
				'散点图':weatherLayer,
				'热点图':heatMapLayer,
				'网格图':heatGridLayer
				};
		var currentLayerType;
		var data;
		function clear(){
			for(var i in layerTypes){
				layerTypes[i].removeAllFeatures();
			}
		}
		function drawPoints(heatMapData,scatterMapData){
			if(drawPoints && scatterMapData){
				data = {heatMapData:heatMapData,scatterMapData:scatterMapData};
			}
			clear();
			currentLayerType = SelectLayerComponent.getCurrentType();
			var layer = layerTypes[currentLayerType];
			switch (currentLayerType){
			case '散点图':drawScatter(data.scatterMapData,layer);break;
			case '热点图':drawHeatPoint(data.heatMapData,layer);break;
			case '网格图':drawHeatGrid(data.heatMapData,layer);break;
			}
		}
		function drawScatter(data,layer){
			var heatPoints = [];
			for(var i in data){
				var value = data[i];
				var p = new SuperMap.Feature.Vector(
						new SuperMap.Geometry.Point(value.lon,value.lat));
				p.style = getPointStyle(value.radius);
				heatPoints.push(p);
			}
			layer.addFeatures(heatPoints);
			layer.setVisibility(true);
			
		}
		function drawHeatPoint(data,layer){
			var heatPoints = [];
			if(currentLayerType == '热点图'){
				layer.radius = radius;//热点图需要
			}
			for(var i in data){
				var value = data[i];
				var p = new SuperMap.Feature.Vector(
						new SuperMap.Geometry.Point(value.lon,value.lat), {
							"value" : 1,//热点图需要
						});
				heatPoints.push(p);
			}
			layer.addFeatures(heatPoints);
			layer.setVisibility(true);
			
		}
		function drawHeatGrid(data,layer){
			var heatPoints = [];
			if(currentLayerType == '网格图'){
				layer.items = getGridLayerItems(data.length);//网格图需要
			}
			for(var i in data){
				var value = data[i];
				var p = new SuperMap.Feature.Vector(
						new SuperMap.Geometry.Point(value.lon,value.lat));
				p.style = getPointStyle();
				heatPoints.push(p);
			}
			layer.addFeatures(heatPoints);
			layer.setVisibility(true);
			
		}
		function getPointStyle(value){
			value = value?value:0;
			return {
					fillColor : "red",
					strokeColor : "yellow",
					pointRadius : 5+value*3
			};
		}
		function getGridLayerItems(max){
			var colors = ['#FFDD55','#FFAA33','#EE7700','orangeRed','red','#AA0000'];
			var strokeColor = 'orange';
			var items = [];
			var last = 1;
			var length = colors.length > Math.ceil(max/2)?Math.ceil(max/2):colors.length;
			var countStep = max/length/3*2;//取最大值的三分之二分级
			for(var i=0;i<length;i++){
				var end = Math.ceil((i+1)*countStep);
				items.push({
					start:last,
					end:end,
					style:{
						strokeColor:strokeColor,
						strokeWidth:1,
						fillColor:colors[i],
						fillOpacity:0.7
					}
				});
				last = end;
			}
			items[items.length-1].end = max+1;
			return items;
		}
		
		return {
			draw:drawPoints,
			redraw:function(){
				drawPoints();
			},
			clear:clear
		};
	})();
	return {
		show:show,
		setReason:function(reason){
			currentReason = reason;
			return this;
		},
		hide:hide
	};
}
